package sourceagile.server.subversionFileRepository.edit;

import java.io.ByteArrayInputStream;

import org.tmatesoft.svn.core.SVNException;
import org.tmatesoft.svn.core.io.ISVNEditor;
import org.tmatesoft.svn.core.io.SVNRepository;
import org.tmatesoft.svn.core.io.diff.SVNDeltaGenerator;

import sourceagile.server.subversionFileRepository.SubversionRepositoryConnection;

/**
 * 
 * @Feature
 */
public class EditFile {

	public static void update(String repositoryURL, String username,
			String password, String filePath, String fileName,
			String fileNewContent) {

		try {

			SVNRepository repository = SubversionRepositoryConnection.connect(
					repositoryURL, username, password);

			String filePathName = filePath + "/" + fileName;

			String logMessage = "Editing file: " + filePath;

			ISVNEditor repositoryEditor;

			repositoryEditor = repository.getCommitEditor(logMessage, null);

			repositoryEditor.openRoot(-1);

			repositoryEditor.openDir(filePath, -1);

			repositoryEditor.openFile(filePathName, -1);

			repositoryEditor.applyTextDelta(filePathName, null);

			SVNDeltaGenerator deltaGenerator = new SVNDeltaGenerator();
			String checksum = deltaGenerator.sendDelta(filePath,
					new ByteArrayInputStream(fileNewContent.getBytes()),
					repositoryEditor, true);

			repositoryEditor.closeFile(filePathName, checksum);

			repositoryEditor.closeDir();

			repositoryEditor.closeEdit();

		} catch (SVNException e) {

			e.printStackTrace();
		}
	}

}
